package com.zksk.admin.controller.product;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.zksk.admin.api.domain.SysDictData;
import com.zksk.admin.api.domain.SysRole;
import com.zksk.admin.domain.product.vo.ProductEnumRequestVo;
import com.zksk.admin.service.product.ProductService;
import com.zksk.common.core.constant.ProductConstants;
import com.zksk.common.core.constant.UserConstants;
import com.zksk.common.core.domain.R;
import com.zksk.common.core.utils.ListPageUtils;
import com.zksk.common.core.web.controller.BaseController;
import com.zksk.common.core.web.domain.AjaxResult;
import com.zksk.common.core.web.page.TableDataInfo;
import com.zksk.common.log.annotation.Log;
import com.zksk.common.log.enums.BusinessType;
import com.zksk.common.redis.service.RedisService;
import com.zksk.common.security.annotation.RequiresPermissions;
import com.zksk.common.security.utils.SecurityUtils;
import com.zksk.mbg.admin.domain.ProductEnum;
import com.zksk.mbg.admin.domain.ProductRelease;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 产品信息
 *
 * @author zksk
 */
@Slf4j
@RestController
@RequestMapping("/product")
@Api(tags = "产品信息相关接口")
public class ProductContrller extends BaseController {
    @Autowired
    private ProductService productService;

    @Autowired
    private RedisService redisService;
    /**
     * 获取产品列表
     */
    @PostMapping("/list")
    @ApiOperation(value = "获取产品列表")
    public TableDataInfo list(@RequestBody ProductEnumRequestVo requestVo){

        if (redisService.hasKey(ProductConstants.REDIS_PRODUCT_ENUM_KEY)){
            Map<String, ProductEnum> cacheMap = redisService.getCacheMap(ProductConstants.REDIS_PRODUCT_ENUM_KEY);
            if (!cacheMap.isEmpty()){
                List list=null;
                if ((requestVo.getProductEnumName())==null){
                   list=new ArrayList<>(cacheMap.values());
                }else{
                    list=new ArrayList<>();
                    for (ProductEnum pro : cacheMap.values()) {
                        if (pro.getName().contains(requestVo.getProductEnumName())){
                            list.add(pro);
                        }
                    }
                }
                PageInfo pageInfo = ListPageUtils.getPageInfo(requestVo.getPageNum(), requestVo.getPageSize(), list);
                return getDataTable(pageInfo);

            }
        }
        ProductEnum productEnum = new ProductEnum();
        productEnum.setName(requestVo.getProductEnumName());
        List<ProductEnum> list = productService.selectProductList(productEnum);
        for (ProductEnum anEnum : list) {
            redisService.setCacheMapValue(ProductConstants.REDIS_PRODUCT_ENUM_KEY,anEnum.getId().toString(),anEnum);
        }
        PageInfo pageInfo = ListPageUtils.getPageInfo(requestVo.getPageNum(), requestVo.getPageSize(), list);
        return getDataTable(pageInfo);
    }

    /**
     * 根据产品id获取详细信息
     */
    @GetMapping(value = "/{id}")
    @ApiOperation(value = "根据产品id获取详细信息")
    public AjaxResult getInfo(@PathVariable Long id)
    {
        if (redisService.hasKey(ProductConstants.REDIS_PRODUCT_ENUM_KEY)){
            ProductEnum productEnum=redisService.getCacheMapValue(ProductConstants.REDIS_PRODUCT_ENUM_KEY,id.toString());
            if (productEnum!=null){
                return success(productEnum);
            }
        }
        return success(productService.selectProductById(id));
    }

    /**
     * 新增产品
     */
    @Transactional(rollbackFor = Exception.class)
    @Log(title = "产品管理", businessType = BusinessType.INSERT)
    @ApiOperation(value = "新增产品")
    @PostMapping
    public R add(@Validated @RequestBody ProductEnum productEnum)
    {
        if (UserConstants.NOT_UNIQUE.equals(productService.checkProductNameUnique(productEnum)))
        {
            return R.fail("新增产品'" + productEnum.getName() + "'失败，产品名称已存在");
        }
        productEnum.setCode(productEnum.getRefBussiness());
        productEnum.setCreateBy(SecurityUtils.getUsername());

        if (productService.save(productEnum)){
            QueryWrapper<ProductEnum> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("name",productEnum.getName());
            ProductEnum one = productService.getOne(queryWrapper);
            redisService.setCacheMapValue(ProductConstants.REDIS_PRODUCT_ENUM_KEY,one.getId().toString(),one);
            return R.ok("新增成功");
        }
        return R.fail("新增失败");
    }

    /**
     * 删除产品
     */
    @Log(title = "产品管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{productIds}")
    @ApiOperation(value = "删除产品")
    public R remove(@PathVariable Long[] productIds)
    {
        if (redisService.hasKey(ProductConstants.REDIS_PRODUCT_ENUM_KEY)){
            for (Long productId : productIds) {
                redisService.deleteCacheMapValue(ProductConstants.REDIS_PRODUCT_ENUM_KEY,productId.toString());
            }
            if (productService.removeByIds(Arrays.asList(productIds))){
                return R.ok("删除成功");
            }

        }
        return R.fail("删除失败");
    }

    /**
     * 修改保存产品
     */
    @Log(title = "产品管理", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "修改保存产品")
    @PutMapping
    public R edit(@Validated @RequestBody ProductEnum productEnum)
    {
        productEnum.setUpdateBy(SecurityUtils.getUsername());
        if (productService.updateById(productEnum)){
            if (redisService.hasKey(ProductConstants.REDIS_PRODUCT_ENUM_KEY)){
                redisService.setCacheMapValue(ProductConstants.REDIS_PRODUCT_ENUM_KEY,productEnum.getId().toString(),productEnum);
                return R.ok("修改成功");
            }
        }
        return R.fail("修改失败");
    }


}
